package bss

import (
    "fcs-api/src/app/model"
    "fcs-api/src/client/rabbitmq"
    "time"

    "github.com/streadway/amqp"
    "git.inspur.com/x/common/loggerfactory"
)

var mq rabbitmq.MqClient
var logger = loggerfactory.GetLogger()

func ListenBssMq() {
    for {
        var err error
        mq, err = rabbitmq.InitClient(model.Base.BssMqInfo.Url)
        if err != nil {
            _ = logger.Error("Init bss mq client error: ", err)
        } else {
            break
        }
        logger.Info("reconnect bss mq...")
        time.Sleep(1 * time.Minute)
    }
    logger.Info("Receiving bss mq message ...")

    //listen mq status and reconnect
    go func() {
        reason, ok := <-mq.NotifyClose(make(chan *amqp.Error))
        // exit this goroutine if closed by developer
        if !ok {
            logger.Info("bss mq connection closed")
        }
        logger.Info("bss mq connection closed, reason:", reason)
        logger.Info("re init bss mq")
        ListenBssMq()
    }()
    err := mq.Receive(model.Base.BssMqInfo.Exchange, model.Base.BssMqInfo.OrderQueue, model.Base.BssMqInfo.OrderRouteKey, receiveOrder)
    if err != nil {
        _ = logger.Error("Receive bss order mq error: ", err)
    }
    err = mq.Receive(model.Base.BssMqInfo.Exchange, model.Base.BssMqInfo.ChangeQueue, model.Base.BssMqInfo.ChangeRouteKey, receiveStatus)
    if err != nil {
        _ = logger.Error("Receive bss change mq error: ", err)
    }
}
